package me.rvj.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @program: JavaWeb
 * @description: JDBC工具类
 * @author: Rv_Jiang
 * @date: 2021/7/2 0:02
 */
public class DBUtil {
    private static DataSource source;

    /**
     * @description 获取DataSource配置
     * @author Rv_Jiang
     * @date 2021/5/29 13:12
     */
    static {
        Properties pros = new Properties();
        InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            pros.load(is);
            source = DruidDataSourceFactory.createDataSource(pros);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @description 连接数据库
     * @author Rv_Jiang
     * @date 2021/5/29 13:11
     */
    public static Connection getConnection() throws SQLException {
        return source.getConnection();
    }

    /**
     * @description 清理内存
     * @author Rv_Jiang
     * @date 2021/5/29 13:48
     */
    public static void clear(Connection conn, Statement ps, ResultSet rs) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
